package com.cya.lotterysystem.common.utils;

import com.cya.lotterysystem.common.pojo.CommonResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/10/27 15:36
 * @description：
 * @modified By：
 * @version:
 */
public class JacksonUtil {

    private JacksonUtil(){

    }

    private final static ObjectMapper objectMapper ;
    static {
        objectMapper=new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper(){
        return objectMapper;
    }
    private static  <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JsonParseException.class);

    }

    private static  <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            Exception ex = var4;
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
                throw new IllegalStateException(ex);
        }
    }
//    序列化

    /**
     *
     * @param object
     * @return
     */
    public static String writeValueAsString(Object object){
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().writeValueAsString(object);
        });
    }

    /**
     * 反序列化
     * @param content
     * @param valueType
     * @return
     * @param <T>
     */
    public static <T> T readValue(String content,Class<T> valueType){
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(content,valueType);
        });
    }

    /**
     * 反序列化List
     * @param content
     * @param paramClass
     * @return
     * @param <T>
     * @throws JsonProcessingException
     */
    public static <T> T readListValue(String content,Class<?> paramClass) throws JsonProcessingException {
        JavaType javaType= JacksonUtil.getObjectMapper().getTypeFactory()
                .constructParametricType(List.class, paramClass);
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(content,javaType);

        });
        }

}